<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { Search, Promotion, Finished, Refresh } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
// import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import {
  getcaptureNewApi,
  getOrderListNewApi,
  pushPddNewOrder,
  getShopInfo,
  getOrderInfo,
  getCidInfoApi
} from "@/api/capture"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
import { useUserStore } from "@/store/modules/user"
import { useCommonStore } from "@/store/modules/common"
import { shortcuts } from "@/utils/dateSet"

defineOptions({
  name: "CaptureList"
})

// #region 获取code
const { currentRoute } = useRouter()
const router = useRouter()
const route = currentRoute.value
const code = route.query.code
const currentBtninfo = ref<string>("获取PDD授权 ")
const btnDis = ref<boolean>(false)
const switchBoo = ref<boolean>(true)
const seeState = ref<string>("")
const searchFormRef = ref<FormInstance | null>(null)
const userStore = useUserStore()
const commonStore = useCommonStore()
const index = ref<any>()
const clientId = ref<any>("")
const orderStatusList = ref<any>([
  {
    value: 1,
    label: "待发货"
  },
  {
    value: 2,
    label: "已发货代签收"
  },
  {
    value: 3,
    label: "已签收"
  },
  {
    value: 5,
    label: "全部"
  }
])
const refundStatusList = ref<any>([
  {
    value: 1,
    label: "无售后或售后关闭"
  },
  {
    value: 2,
    label: "售后处理中"
  },
  {
    value: 3,
    label: "退款中"
  },
  {
    value: 4,
    label: "退款成功"
  },
  {
    value: 5,
    label: "全部"
  }
])
const options = ref<any>([
  {
    value: 1,
    label: "待发货"
  },
  {
    value: 2,
    label: "已发货代签收"
  },
  {
    value: 3,
    label: "已签收"
  }
])
const formData = reactive<any>({ data: {} })
//获取账号对应授权配置
const getAuth = async () => {
  await getShopInfo({
    userId: userStore.usernameID
  }).then((res: any) => {
    // console.log(res.data)
    index.value = res.data.index
    clientId.value = res.data.clientId
  })
}
const getcode = async () => {
  await getAuth()

  await getcaptureNewApi({
    code: code,
    index: index.value
  }).then((res) => {
    if (res.code == 200) {
      currentBtninfo.value = "已授权"
      btnDis.value = true
      router.push("/capture-order/capture-list-plus")
    }
  })
}
if (code) {
  getcode()
}

// #endregion
// getcaptureInfo({
//   orderId: "230816-353600849593658",
//   data: ["$J5immzY3aYb1$AgAAAAI+gooGU7SapQB3vHfVNGdUOrJB/jFuXdpb6gs=$0$$"]
// }).then((res: any) => {
//   console.log(res)
// })

const loading = ref<boolean>(false)
const arr1 = ref<any>([])
// #region 查
const tableData = ref<any>([])
const searchData = reactive<any>({
  time: "",
  refund_status: 5,
  order_status: 5,
  orderId: ""
})
const getTableData = async () => {
  await getAuth()
  if (searchData.orderId) {
    await getOrderInfo({
      orderId: searchData.orderId,
      index: index.value
    }).then((res: any) => {
      tableData.value = [res.data]
      tableData.value.forEach((item: any) => {
        getCidInfoApi({ orderId: item.order_sn, index: index.value }).then((res: any) => {
          item.id_card_name = res.data.order_virtual_information_response.id_card_name
          item.id_card_num = res.data.order_virtual_information_response.id_card_num
        })
        // if (!Number(item.item_list[0].outer_id) || Number(item.item_list[0].outer_id) > 1000) {
        //   item.item_list[0].outer_id = ""
        // }
      })
      arr1.value = tableData.value
    })
  } else {
    if (!searchData.time) {
      searchData.time = []
    }
    await getOrderListNewApi({
      start:
        new Date(searchData.time[0]).getTime() / 1000 || new Date(new Date().toLocaleDateString()).getTime() / 1000,
      end: new Date(searchData.time[1]).getTime() / 1000 || Math.floor(new Date().getTime() / 1000),
      refund_status: searchData.refund_status,
      order_status: searchData.order_status,
      page: paginationData.currentPage,
      size: paginationData.pageSize,
      index: index.value
    })
      .then((res) => {
        if (res.code == 200) {
          tableData.value = res.data.order_list_get_response.order_list
          arr1.value = tableData.value
          currentBtninfo.value = "已授权"
          btnDis.value = true
          router.push("/capture-order/capture-list-plus")
        } else {
          currentBtninfo.value = "获取PDD授权"
          btnDis.value = false
        }
        paginationData.total = res.data.order_list_get_response.total_count
      })
      .catch(() => {
        currentBtninfo.value = "获取PDD授权"
        btnDis.value = false
      })
      .finally(() => {
        switchBoo.value = false
      })
  }
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

// #endregion
const tableRef = ref<any>(null)
const dataArr = ref<any>([])
const dialogVisible = ref<boolean>(false)
const currentUpdateId = ref<undefined | string>(undefined)
const fz = ref<any>({})
const handleAdd = (row: any) => {
  currentUpdateId.value = row.order_sn
  seeState.value = "update"
  fz.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
  rowData(fz.value, false)
  dataArr.value.push(fz.value)
}

//批量提交方法
const pushPdd = async (data: any) => {
  console.log(data, 33)

  await pushPddNewOrder(data, index.value).then((res: any) => {
    // console.log(res, 1923)
    if (res.code == 200) {
      ElMessage.success(res.message)
      dataArr.value = []
      tableRef.value?.clearSelection()
      getTableData()
    }
  })
}

//查看详情
const handleSeeInfo = (row: any) => {
  console.log(1)
  seeState.value = "see"
  rowData(row, false)
  dataArr.value.push(row)
}
// row通用
const rowData = async (row: any, PL: boolean) => {
  formData.data = row
  formData.data.order_sn = row.order_sn
  formData.data.remark = row.remark
  formData.data.order_status = row.order_status
  formData.data.created_time = row.created_time
  formData.data.receiver_name = row.receiver_name
  formData.data.receiver_phone = row.receiver_phone
  formData.data.goods_name = row?.item_list[0].goods_name
  formData.data.goods_img = row?.item_list[0].goods_img
  formData.data.goods_spec = row?.item_list[0].goods_spec
  // loading.value = true
  if (!PL) {
    dialogVisible.value = true
    // dataArr.value.push(formData.data)
  } else {
    dataArr.value.push(row)
    console.log(row.id_card_name, 10923)
  }
}

//批量选择
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  if (val.length) {
    val.forEach((item: any) => {
      if (!item.item_list[0].outer_id) {
        // ElMessage.warning("请匹配套餐")
        tableRef.value?.clearSelection()
        return
      }
      rowData(item, true)
      console.log(item, 2)
    })
  }
  console.log(val.length)
}
//批量提交
const addItems = async () => {
  console.log(dataArr.value.length, "长度")

  // if (dataArr.value.length)
  pushPdd(dataArr.value)
}

//单次提交
const handleCreate = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await pushPdd(dataArr.value)
      dialogVisible.value = false
    } else {
      return false
    }
  })
}

//复制编码
import useClipboard from "vue-clipboard3"

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}

//  #region 清除规则报错信息
const formRef = ref<FormInstance | null>(null)
// 增改弹出框验证
const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入姓名" }]
})
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  seeState.value = ""
  dataArr.value = []
  clearValidate()
}
// #endregion

// #region 套餐
import { getComboDataApi } from "@/api/combo-jd"
const comboList = ref<any>([])
getComboDataApi({
  page: 1,
  size: 10000,
  type: "pdd",
  userId: userStore.usernameID
}).then((res: any) => {
  comboList.value = res.data.list
})

watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, {
  immediate: true
})
watch([() => switchBoo.value], (newValue) => {
  const arr = ref<any>([])
  if (newValue[0]) {
    tableData.value.forEach((item: any) => {
      if (item?.remark_tag == 1) {
        arr.value.push(item)
      }
      tableData.value = arr.value
    })
  } else {
    tableData.value = arr1.value
  }
})
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
//授权跳转
const goEmpower = () => {
  window.location.href = `https://fuwu.pinduoduo.com/service-market/auth?response_type=code&client_id=${clientId.value}&redirect_uri=${commonStore.BASEURL}/company/%23/capture-order/capture-list-plus&state=true`
}

/**加密 */
const toHideString = (val: any, len: any) => {
  if (val.length == 2) {
    return `${val.substring(0, len)}*****${val.substring(val.length)}`
  } else {
    return `${val.substring(0, len)}*****${val.substring(val.length - len)}`
  }
}
// 截取字符串
const getMiddleChars = (str: any, start: any, length: any) => {
  return str.substring(start, start + length)
}
</script>
<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="orderId" label="订单编号">
          <el-input v-model="searchData.orderId" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item prop="order_status" label="发货状态">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select v-model="searchData.order_status" clearable placeholder="请选择" style="width: 200px">
            <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="refund_status" label="售后状态">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select v-model="searchData.refund_status" clearable placeholder="请选择" style="width: 200px">
            <el-option v-for="item in refundStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button type="primary" :icon="Promotion" style="margin-left: 10px" :disabled="btnDis" @click="goEmpower">
            <el-link
              :disabled="btnDis"
              style="color: #fff"
              :href="`https://fuwu.pinduoduo.com/service-market/auth?response_type=code&client_id=${clientId.value}&redirect_uri=${commonStore.BASEURL}/company/%23/capture-order/capture-list-plus&state=true`"
              >{{ currentBtninfo }}</el-link
            >
          </el-button>
        </el-form-item>
      </el-form>

      <p style="color: #666; font-size: 14px">
        <span style="color: red">提示：</span>
        <span
          >店铺平台若配置了与本系统对应的套餐ID，可自动匹配套餐，若无配置需手动匹配,未匹配状态下无法进行批量提交，提交前请先检查</span
        >
      </p>
      <el-form-item label="只看红旗" style="font-size: 14px">
        <el-switch v-model="switchBoo" />
      </el-form-item>
      <el-button type="primary" :icon="Finished" @click="addItems">批量提交</el-button>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="order_sn" label="订单编号" align="center" />
          <el-table-column label="商品信息" align="center" width="300">
            <template #default="scope">
              <div class="goodInfo" v-for="item in scope.row.item_list" :key="item.goods_id">
                <el-row>
                  <el-col :span="8" style="text-align: center; vertical-align: middle">
                    <p><img :src="item.goods_img" alt="" width="50" height="50" /></p>
                  </el-col>
                  <el-col :span="16">
                    <!-- <p :title="item.goods_name" class="esp">{{ item.goods_name }}</p> -->
                    <!-- <p>{{ item.sku_id }}</p> -->
                    <p :title="item.goods_spec">{{ item.goods_spec }}</p>
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="套餐匹配" align="center" width="360">
            <template #default="scope">
              <el-select v-model="scope.row.item_list[0].outer_id" clearable filterable placeholder="请选套餐">
                <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
              </el-select>
              <el-link type="primary" style="margin-left: 10px" @click="copy(scope.row.item_list[0].outer_id)"
                ><el-icon><DocumentCopy /></el-icon>复制编码</el-link
              >
            </template>
          </el-table-column>
          <el-table-column prop="created_time" label="下单时间" align="center" />
          <el-table-column label="证件年龄" align="center">
            <template #default="scope">
              <p>{{ getMiddleChars(scope.row.id_card_num, 6, 8) }}</p>
            </template>
          </el-table-column>
          <el-table-column label="收件信息" align="center">
            <template #default="scope">
              <p>{{ scope.row.receiver_name }}</p>
              <p>{{ toHideString(scope.row.receiver_phone, 3) }}</p>
              <p>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.town }}{{ scope.row.receiver_address }}</p>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="cardName" label="身份证信息" align="center">
            <template #default="scope">
              <p>{{ scope.row.id_card_name }}</p>
              <p>{{ scope.row.id_card_num }}</p>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="cardId" label="买家备注" align="center" /> -->
          <el-table-column prop="consignee" label="卖家备注(颜色)" align="center">
            <template #default="scope">
              <p>
                <span
                  class="flag"
                  :class="{
                    red: scope.row.remark_tag == 1,
                    yellow: scope.row.remark_tag == 2,
                    green: scope.row.remark_tag == 3,
                    blue: scope.row.remark_tag == 4,
                    purple: scope.row.remark_tag == 5
                  }"
                />
                {{ scope.row.remark_tag_name }}
              </p>
              <p :title="scope.row.remark" class="esp">{{ scope.row.remark }}</p>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <p v-if="scope.row.order_status == 1">待发货</p>
              <p v-if="scope.row.order_status == 2">已发货代签收</p>
              <p v-if="scope.row.order_status == 3">已签收</p>
            </template>
          </el-table-column>
          <el-table-column label="售后状态" align="center">
            <template #default="scope">
              <p v-if="scope.row.refund_status == 1">无售后或售后关闭</p>
              <p v-if="scope.row.refund_status == 2">售后处理中</p>
              <p v-if="scope.row.refund_status == 3">退款中</p>
              <p v-if="scope.row.refund_status == 4">退款成功</p>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleAdd(scope.row)">修改提交</el-button>
              <br />
              <el-button type="primary" text bg size="small" @click="handleSeeInfo(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="[10, 20]"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="seeState === 'see' ? '查看详情' : '修改提交'"
      @close="resetForm"
      width="60%"
      v-loading="loading"
    >
      <el-form ref="formRef" :model="formData.data" :rules="formRules" label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="order_sn" label="订单编号">
              <el-input v-model="formData.data.order_sn" placeholder="请输入订单编号" :disabled="seeState === 'see'" />
            </el-form-item>
            <div>
              <h4>身份证信息:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="id_card_name" label="姓名">
                  <el-input
                    v-model="formData.data.id_card_name"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="id_card_num" label="身份证号">
                  <el-input
                    v-model="formData.data.id_card_num"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
              </div>
            </div>
            <div>
              <h4>备注:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="remark" label="卖家备注">
                  <el-input
                    v-model="formData.data.remark"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="order_status" label="订单状态">
                  <el-select
                    v-model="formData.data.order_status"
                    class="m-2"
                    placeholder="请选择"
                    size="large"
                    :disabled="seeState === 'see'"
                  >
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单时间" prop="created_time">
              <el-input v-model="formData.data.created_time" placeholder="请输入" :disabled="seeState === 'see'" />
            </el-form-item>
            <div>
              <h4>商品信息:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="goods_name" label="套餐名">
                  <el-input
                    v-model="formData.data.goods_name"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="goods_name" label="套餐主图">
                  <div class="demo-image__preview">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="formData.data.goods_img"
                      :zoom-rate="1.2"
                      :initial-index="4"
                      fit="cover"
                    />
                  </div>
                </el-form-item>
                <el-form-item prop="goods_spec" label="套餐详情">
                  <el-input
                    v-model="formData.data.goods_spec"
                    placeholder="请输入"
                    type="textarea"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
              </div>
            </div>
            <div>
              <h4>匹配系统套餐:</h4>
              <el-form-item prop="item_list[0].outer_id" label="匹配系统套餐">
                <el-select
                  v-model="formData.data.item_list[0].outer_id"
                  clearable
                  filterable
                  placeholder="请选套餐"
                  :disabled="seeState === 'see'"
                >
                  <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
                </el-select>
              </el-form-item>
            </div>
            <div>
              <h4>收件信息:</h4>
              <div style="padding-left: 20px">
                <el-form-item prop="receiver_name" label="收件人">
                  <el-input v-model="formData.data.id_card_name" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="receiver_phone" label="手机号">
                  <el-input
                    v-model="formData.data.receiver_phone"
                    placeholder="请输入"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
                <el-form-item prop="province" label="省">
                  <el-input v-model="formData.data.province" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="city" label="市">
                  <el-input v-model="formData.data.city" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="town" label="区">
                  <el-input v-model="formData.data.town" placeholder="请输入" :disabled="seeState === 'see'" />
                </el-form-item>
                <el-form-item prop="receiver_address" label="详细地址">
                  <el-input
                    v-model="formData.data.receiver_address"
                    placeholder="请输入"
                    :disabled="seeState === 'see'"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  .btn {
    width: 100%;
    height: 100%;
    display: flex;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.pbox {
  line-height: 2em;
}
.flag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.red {
  background: red;
}
.yellow {
  background: rgb(255, 220, 0);
}
.green {
  background: green;
}
.blue {
  background: blue;
}
.purple {
  background: purple;
}
.goodInfo {
  text-align: left;
}
.esp {
  width: 180px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
